const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/messQuery/messQuery');
const queryUser = require('../../db/userQuery/userQuery');

//解析token
const {
    token_verify
} = require('../../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

//获取留言板列表
router.get('/messList', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    pool.query(query.select_mess, [count, page], (error, result) => {
        if (error) {
            logger().error(`获取留言板列表错误: ${error}`);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取社区留言板信息成功", data));
        }
    });
})

//发送留言留言板消息
router.post('/sendMess', function (req, res) {
    const token = req.headers.authorization;
    const {
        openId
    } = token_verify(token);
    pool.query(queryUser.getUser_info, openId, (error, result) => {
        if (error) {
            logger().error(`发送留言留言板消息错误: ${error}`);
        } else {
            const author = result[0].nickName;
            const avatarUrl = result[0].avatarUrl;
            const content = req.body.content;
            const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
            pool.query(query.add_mess, [author, avatarUrl, content, time], (error, result) => {
                if (error) {
                    logger().error(`发送留言留言板消息错误: ${error}`);
                    res.json(Response.error("留言失败", null));
                } else {
                    res.json(Response.success("留言成功", null));
                }
            });
        }
    });

})


module.exports = router;